//
//  SHBooks.m
//  SDemo
//
//  Created by gg on 2018/8/8.
//  Copyright © 2018年 gg. All rights reserved.
//

#import "SHBooks.h"
#import <objc/message.h>
@implementation SHBooks

#pragma mark ---- runtime + kvc -----
//这个方法在nslog 时候会调用
-(NSString *)description {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    unsigned int count = 0;
//    Ivar *ivarArr = class_copyIvarList([self class], &count);
//    for (int i = 0; i < count; i ++) {
//        Ivar ivar = ivarArr[i];
//        NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
//        NSLog(@"name : %@",name);
//        id value = [self valueForKey:name];
//
//        if (value) {
//            [dic setObject:value forKey:name];
//        }
//    }
//    return [NSString stringWithFormat:@"%@ : %@",[self class], dic];
    
    objc_property_t *proertyArr =  class_copyPropertyList([self class], &count);
    for (int i = 0; i < count; i ++) {
        objc_property_t property = proertyArr[i];
        NSString *name = [NSString stringWithUTF8String:property_getName(property)];
        NSLog(@"name : %@",name);
        id value  = [self valueForKey:name] ? : [NSNull null];
        [dic setObject:value forKey:name];
        
    }

    return [NSString stringWithFormat:@"%@ : %@",[self class],dic];
}


-(instancetype)initWithDic:(NSDictionary *)dic {
    if (self = [super init]) {
        
//        for (NSString *key in dic) {
//            id value = dic[key];
//            [self setValue:value forKey:key];
//
//        }
        //可以用下面的方法替代上面的过程
        [self setValuesForKeysWithDictionary:dic];
    }
    
    return self;
}

-(void)setValue:(id)value forUndefinedKey:(NSString *)key {
    NSLog(@"不存在key : %@",key);
}

-(void)setNilValueForKey:(NSString *)key {
    NSLog(@"属性值不能为nil");
}

+(instancetype)bookswithDic:(NSDictionary *)dic {
     return [[self alloc] initWithDic:dic];
}




//这个方法会在控制台po出来的试试，会调用
-(NSString *)debugDescription {
    
    return @"this is debug description";
}

@end
